<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Utils\ResponseUtil;
use Illuminate\Support\Str;

class UploadController extends Controller
{

    // 返回 相对storage的路径
    private function doUpload($fileKey='file'){
        $request = request();
        $file = $request -> file($fileKey);
        $dir = '/uploads/'.date("Y-m-d");
        $path = storage_path('app') . $dir;
        if (!file_exists($path)){
            mkdir($path,0777,1);
        }
        //相对storage的路径

        $path = $file->storeAs($dir,Str::random(16).'.'.$file->getClientOriginalExtension());
        return $path;
    }

    public function upload(){
        $request = request();
        $path = $this->doUpload('file');
        return ResponseUtil::success(['path'=>$path,'post'=>$request->post()]);
    }


    public function config(){
        $request = request();

        $path = $this->configUpload('file');
        return ResponseUtil::success(['path'=>$path,'post'=>$request->post()]);
    }


    // 返回 相对storage的路径
    private function configUpload($fileKey='file'){
        $request = request();
        $file = $request -> file($fileKey);
        $dir = '/uploads/Config';
        $path = storage_path('app') . $dir;
        if (!file_exists($path)){
            mkdir($path,0777,1);
        }
        // 删除 $path 目录下的所有文件
        $this->deleteFilesInDir($path);
        $filename = Str::uuid() . '.' . $file->getClientOriginalExtension();
        //相对storage的路径
        $path = $file->storeAs($dir,$filename);
        return $path;
    }

    private function deleteFilesInDir($directory)
    {
        if (is_dir($directory)) {
            $files = glob($directory . '/*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
        }
    }

    public function wangEditor(){
        $baseUrl = config('app.web_url');
        $path = $this->doUpload('wangeditor-uploaded-image');
        return ResponseUtil::json([
            'errno'=>0,
            'data'=>[
                'url'=>$baseUrl . $path,
            ]
        ]);
    }

}
